package com.npl.demonplservice;

import java.util.List;
import com.ansj.vec.Word2VEC;

/**
 * Created by frankqian on 2018/7/23.
 */
public class Similarity {
    public static float[] getWordVector(String word) {
        Word2VEC vec = new Word2VEC();
        return vec.getWordVector(word);
    }

    private static double calDist(float[] vec1, float[] vec2) {
        float dist = 0;
        for (int i = 0; i < vec1.length; i++) {
            dist += vec1[i] * vec2[i];
        }
        return dist;
    }

    private static double wordSimilarity(String word1, String word2) {
        float[] word1Vec = getWordVector(word1);
        float[] word2Vec = getWordVector(word2);
        if(word1Vec == null || word2Vec == null) {
            return 0;
        }
        return calDist(word1Vec, word2Vec);
    }

    private static double calMaxSimilarity(String centerWord, List<String> wordlist) {
        double max = -1.0;
        if (wordlist.contains(centerWord))
            return 1.0;
        else {
            for (String word: wordlist) {
                double temp = wordSimilarity(centerWord, word);
                if (temp==0) continue;
                if (temp>max) {
                    max = temp;
                }
            }
        }
        return (max==-1.0)?0:max;
    }

    public static double getsimilarity(List<String> sentence1Words, List<String> sentence2Words) {
        if (sentence1Words.isEmpty() || sentence2Words.isEmpty()) {
            return 0;
        }
        double sum1 = 0;
        double sum2 = 0;
        int count1 = 0;
        int count2 = 0;
        for (int i = 0; i < sentence1Words.size(); i++) {
            if (getWordVector(sentence1Words.get(i)) != null) {
                count1++;
                sum1 += calMaxSimilarity(sentence1Words.get(i), sentence2Words);
            }
        }
        for (int i = 0; i < sentence2Words.size(); i++) {
            if (getWordVector(sentence2Words.get(i)) != null) {
                count2++;
                sum2 += calMaxSimilarity(sentence2Words.get(i), sentence1Words);
            }
        }
        return (sum1 + sum2) / (count1 + count2);
    }
}
